import React from 'react'
import styles from '@/assets/css/confirm.module.css';


export default () =>
{
    const [roomid] = useState(React.params('roomid') ?? 0)

    let [room, SetRoom] = useState({flag_text: [], price: 0, thumb_text: '', name: '', })
    let [guest, SetGuest] = useState([])
    let [coupon, SetCoupon] = useState<any>([])
    let [dateshow, SetDateShow] = useState(false)
    let [guestshow, SetGuestShow] = useState(false)
    let [couponshow, SetCouponShow] = useState(false)
    let [payshow, SetPayshow] = React.useState(false)
    // 价格
    let [price, SetPrice] = React.useState(0)
    // 原价
    let [originprice, SetOriginprice] = React.useState(0)
    // 天数
    let [day, SetDay] = React.useState(0);

    //支付信息
    const [paylist] = React.useState([[
        { label: '余额支付', value: 'money' },
        { label: '微信支付', value: 'wx' },
        { label: '支付宝支付', value: 'zfb' },
    ]])

    //订单信息
    const [order, SetOrder] = React.useState({
        remark: '',
        //价格信息
        origin_price: 0,
        price: 0,
        //优惠券
        couponid: '',
        couponstr: '暂无优惠券信息',
        //日期
        datestr: '',
        starttime: 0,
        endtime: 0,
        //住客
        guest: '',
        gueststr: '请选择住客信息',
        guestids: [],
        //支付方式
        paystr: '余额支付',
        pay: 'money'
    })

    // 日期组件默认日期
    const defaultDateRange: [Date, Date] = [
        new Date(),
        new Date(new Date().getTime() + 86400000),
    ]
    
    //钩子函数 初始化数据请求
    React.useEffect(() => {
        GetRoomInfoData()
        GetGuestData()
        GetCouponData()
        getCurrentDate()
    }, [roomid])

    //当订单信息有变化，就重新计算价格
    React.useEffect(() => {
        Total()
    }, [order, room])

    //统计价格的方法
    const Total = () => 
    {
        var starttime = order.starttime
        var endtime = order.endtime

        //时间差
        var durationSeconds = endtime - starttime
        var day = Math.floor(durationSeconds / 86400)

        // 原价 时间差*房间原价
        var truncateToTwoDecimals = (num: number) => Math.trunc(num * 100) / 100;
        var origin_price = truncateToTwoDecimals(room.price * day)
        var price = origin_price

        //判断是否有选择优惠券
        if(order.couponid)
        {
            //找出当前选中优惠券的记录
            var CouponActive:any = 0

            if(coupon.length > 0)
            {
                var first = coupon.slice(0, 1)
                CouponActive = first.find((item: any) => item.value = order.couponid)
            }
            
            if(CouponActive)
            {
                //优惠券使用后的实际的价格
                price = truncateToTwoDecimals(price * CouponActive.rate)
            }
        }
        
        //修改价格
        SetPrice(price)
        SetOriginprice(origin_price)
        SetDay(day)
    }

    // 酒店详情
    const GetRoomInfoData = async () => 
    {
        let result = await React.request.post('/room/RoomInfo', {
            roomid: roomid
        })

        if (result && result.code == 1) 
        {
            SetRoom(result.data.info);
        }
    }

    //查询住客人信息
    const GetGuestData = async() =>
    {
        let result = await React.request.post('/room/GuestList', {
            busid: React.business.id,
        })

        if(result.code === 1)
        {
            SetGuest(result.data)
        }
    }

    //确认选择住客信息
    const GuestChange = async (value: string[]) =>
    {
        var gueststr:any = []
        var guestids:any = []

        //循环遍历
        guest.map((item:any) => {
            if(value.includes(item.id))
            {
                gueststr.push(item.nickname)
                guestids.push(item.id)
            }
        })
        
        var str = gueststr.join('、')
        var ids = guestids.join(',')

        //设置到订单数据中
        SetOrder({
            ...order,
            gueststr: str,
            guest: ids,
            guestids,
        })
    }

    // 优惠券列表
    const GetCouponData = async() =>
    {
        let result = await React.request.post('/room/CouponList', {
            busid: React.business.id,
        })

        if(result.code === 1)
        {
            let data:any = [];
            result.data.map((item:any) =>{
                data.push({
                    label: `${item.coupon.title}-${item.coupon.rate*10}折`,
                    value: item.id,
                    rate: item.coupon.rate
                })
            })
            //给二维数组结构
            SetCoupon([data]);
        }
    }


    //初始化默认时间
    const getCurrentDate = () =>
    {
        // `2024-03-20 - 2024-03-25`
        var datestr = `${new Date(defaultDateRange[0]).toLocaleDateString()} - ${new Date(defaultDateRange[1]).toLocaleDateString()}`

        //标准时间转换为时间戳
        var starttime = Date.parse(new Date(defaultDateRange[0]).toLocaleDateString()) / 1000
        var endtime = Date.parse(new Date(defaultDateRange[1]).toLocaleDateString()) / 1000

        SetOrder({
            ...order,
            datestr,
            starttime,
            endtime
        })
    }

    //日期确认
    const DateConfirm = (val: any) => 
    {
        SetDateShow(false)

        // `2024-03-20 - 2024-03-25`
        var datestr = `${new Date(val[0]).toLocaleDateString()} - ${new Date(val[1]).toLocaleDateString()}`

        //标准时间转换为时间戳
        var starttime = Date.parse(new Date(val[0]).toLocaleDateString()) / 1000
        var endtime = Date.parse(new Date(val[1]).toLocaleDateString()) / 1000

        SetOrder({
            ...order,
            datestr,
            starttime,
            endtime
        })
    }

    //优惠券确认
    const CouponChange = (value: any) => 
    {
        SetCouponShow(false)

        var couponstr = ''

        if(coupon.length <= 0)
        {
            React.toast('暂无优惠券')
            return false
        }
        
        //获取picker第一个选项
        var list:any = coupon[0]

        //循环遍历
        list.map((item:any) => {
            if(item.value == value[0])
            {
                couponstr = item.label
            }
        })
        
        //设置订单数据
        SetOrder({
            ...order,
            couponstr,
            couponid: value[0]
        })
    }

    // 支付方式
    const PayChange = async (value: any) => 
    {

        SetPayshow(false)

        var paystr = ''

        //获取picker第一项
        var list: any = paylist[0]

        list.map((item: any) => {
            if (item.value == value[0]) 
            {
                paystr = item.label
            }
        })

        SetOrder({
            ...order,
            paystr,
            pay: value[0],
        })
    }

    // 订单备注
    const RemarkChange = (e:any) =>
    {
        SetOrder({
            ...order,
            remark:e
        })
    }

    //计算总价
    const OrderPrice = () =>
    {
        if(price == originprice)
        {
            return (
                <div className={styles.text}>
                    <span>总价:</span>
                    <span>￥{price}</span>
                </div>
            )
        }else
        {
            return (
                <div className={styles.text}>
                    <span>优惠价格:</span>
                    <span>￥{price}</span>
                    <s>原价：￥{originprice}</s>
                </div>
            )
        }
    }

    //提交订单
    const ConfirmOrder = async () =>
    {
        if(day <= 0)
        {
            return React.toast('请选择入住的日期')
        }

        if(order.guestids.length <= 0)
        {
            return React.toast('请选择住客信息')
        }

        //组装数据
        let data = {
            busid: React.business.id,
            roomid: roomid,
            guest: order.guest,
            starttime: order.starttime,
            endtime: order.endtime,
            couponid: order.couponid ?? '',
            remark: order.remark,
            pay: order.pay
        }

        //判断是否是余额支付
        if(order.pay == 'money')
        {
            let result = await React.request.post('/room/OrderAdd', data)

            if(result.code == 0)
            {
                React.toast(result.msg)
                return false
            }

            React.toast(result.msg, result.url)
            return false
        }else
        {
            //其他类型的支付
            let result = await React.request.post('/room/OrderAdd', data)

            if(result.code == 0)
            {
                return React.toast(result.msg)
            }

            //跳转到收银台界面
            React.toast(result.msg, `/room/pay?payid=${result.data.id}`)
            return false
        }
    }




    return (
        <>
            <div className={styles.skeleton}>
                {/* 房间信息 */}
                <div className={styles.detail}>
                    <div className={styles.thumb}>
                        <img src={room.thumb_text} alt="" />
                    </div>
                    <div className={styles.right}>
                        <p>{room.name}</p>
                        <p>￥{room.price} / 晚</p>
                        <div className={styles.tips}>
                            {room.flag_text && room.flag_text.map((flag: any, index: any) => <span key={index}> {flag} </span>)}
                        </div>
                    </div>
                </div>

                {/* 入住时间 */}
                <div className={styles.skeleton_rect}>
                    <div className={styles.item}>
                        <label>入住日期</label>
                        <React.UI.Input type="text" className={styles.item_right} placeholder="请选择入住日期" value={order.datestr} onClick={() => SetDateShow(true)} />
                    </div>

                    {/* 日期选择 */}
                    <React.UI.CalendarPicker
                        visible={dateshow}
                        min={new Date()}
                        defaultValue={defaultDateRange}
                        selectionMode='range'
                        onClose={() => SetDateShow(false)}
                        onMaskClick={() => SetDateShow(false)}
                        onConfirm={DateConfirm}

                    >
                    </React.UI.CalendarPicker>

                    {/* 住客信息 */}
                    <div className={styles.item}>
                        <label>住客信息</label>
                        <div className={order.guestids.length > 0 ? styles.item_right : styles.item_rights} onClick={() => SetGuestShow(true)}>{order.gueststr}</div>
                    </div>

                    {/* 弹出层 */}
                    <React.UI.Popup
                        visible={guestshow}
                        destroyOnClose
                        onMaskClick={() => SetGuestShow(false)}
                    >
                        <React.UI.CheckList
                            multiple
                            defaultValue={order.guestids}
                            onChange={GuestChange}
                        >
                            {guest && guest.map((item:any, key:number) => (
                                <React.UI.CheckList.Item key={key} value={item.id}>
                                    {item.nickname}（{item.mobile}）
                                </React.UI.CheckList.Item>
                            ))}
                        </React.UI.CheckList>

                        <React.UI.Button color="primary" block style={{ width: '100%' }} onClick={() => SetGuestShow(false)}>确认</React.UI.Button>
                    </React.UI.Popup>



                </div>

                {/* 优惠券 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>优惠券</div>
                    <p>{order.couponstr}</p>
                    <React.UI.Button size="mini" color="primary" onClick={() => SetCouponShow(true)}>选择</React.UI.Button>

                    {/* 弹框选项 */}
                    <React.UI.Picker
                        visible={couponshow}
                        columns={coupon}
                        onClose={() => SetCouponShow(false)}
                        onConfirm={CouponChange}
                    >
                    </React.UI.Picker>


                </div>

                {/* 支付方式 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>支付方式</div>
                    <p>{order.paystr}</p>
                    <React.UI.Button size="mini" color="primary" onClick={() => SetPayshow(true)}>选择</React.UI.Button>

                    <React.UI.Picker
                        columns={paylist}
                        visible={payshow}
                        onClose={() => SetPayshow(false)}
                        onConfirm={PayChange}
                    >
                    </React.UI.Picker>
                </div>

                {/* 订单备注 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>订单备注</div>
                    <React.UI.Input placeholder={'请输入订单备注'} value={order.remark} onChange={RemarkChange} />
                </div>

                {/* 费用 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>房间费用</div>
                    <div className={styles.prices}>
                        <span>￥{originprice}</span>
                        <span>共 {day} 晚</span>
                    </div>
                </div>


            </div>

            <div className={styles.comfirm_foot_bar}>
                <OrderPrice />
                <React.UI.Button onClick={ConfirmOrder} color='primary' shape='rounded'>提交订单</React.UI.Button>
            </div>
        </>
    )
}